package net.zjitc.list;

public class MyArrayList<T> implements MyList<T> {
    private Object[] arr = new Object[3];
    private int index = 0;
    @Override
    public boolean add(T data) {
       //一定要先判断空间是否够用
        Capacity();

        arr[index++] = data;
        return true;
    }


    /**
     * 指定的位置插入一个元素
     * @param index 指定位置
     * @param data
     * @return
     */
    @Override
    public boolean add(int index, T data) {
        //如果索引不在范围内，怎么办？
        if (index <0 || index > this.index){
            throw new RuntimeException("超出索引");
        }
        //如果数组空间不够怎么办？
        Capacity();

        //都满足以上条件的情况下，如何插入？
        for (int i = this.index; i < index; i--) {
            arr[i] = arr[i-1];
        }
        arr[index] = data;
        this.index++;
        return true;
    }

    /**
     * 删除第一个data元素
     * @param data 要删除的元素
     * @return 删除的元素
     */
    @Override
    public T remove(T data) {
        T oldData =null;
        for (int i = 0; i < this.index; i++) {
            if (arr[i].equals(data)){//如果相等，则删除
                oldData = (T)arr[i];
                for (int j = i; j < this.index-1; j++) {
                   arr[j]= arr[j+1];
                }
            }
        }
        return oldData;
    }

    @Override
    public T remove(int index) {
        return null;
    }

    @Override
    public boolean set(int index, T data) {
        if (index <0 || index > this.index){
            throw new RuntimeException("超出索引");
        }
        arr[index] = data;
        return true;
    }


    @Override
    public T getValue(int index) {
        if (index <0 || index > this.index){
            throw new RuntimeException("超出索引");
        }

        return (T)arr[index];
    }

    @Override
    public int size() {
        return index;
    }

    /**
     * 扩容代码，扩容的策略为扩大2倍
     */
    private void Capacity() {
        if (this.index >= arr.length) {
            Object[] temp = new Object[arr.length * 2];
            for (int i = 0; i < arr.length; i++) {
                temp[i] = arr[i];
            }
            arr = temp;
        }
    }

}
